package com.fan.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.fan.pojo.Bill;
import com.fan.pojo.Provider;
import com.fan.pojo.Role;
import com.fan.pojo.User;
import com.fan.service.bill.BillService;
import com.fan.service.bill.BillServiceImpl;
import com.fan.service.provider.ProviderService;
import com.fan.service.provider.ProviderServiceImpl;
import com.fan.service.role.RoleService;
import com.fan.service.role.RoleServiceImpl;
import com.fan.util.Constants;
import com.fan.util.PageSupport;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class BillServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("query")){
            this.query(req,resp);
        }else if (method.equals("add")){
            this.add(req,resp);
        }else if (method.equals("delbill")){
            this.delBill(req,resp);
        }else if (method.equals("view")){
            this.getBillById(req,resp);
        }else if (method.equals("modify")){
            this.modify(req,resp);
        }else if (method.equals("modifyexe")){
            this.modifyexe(req,resp);
        }else if (method.equals("getproviderlist")){
            this.getProviderList(req,resp);
        }
    }

    private void getBillById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(id)){
            BillService billService = new BillServiceImpl();
            Bill bill = billService.getBillById(id);
            req.setAttribute("bill",bill);
            req.getRequestDispatcher("/jsp/billview.jsp").forward(req,resp);
        }
    }

    private void delBill(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("billid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(id);
        }catch (Exception e){
            delId = 0;
        }
        HashMap<String,String> resultMap = new HashMap<>();
        if (delId <= 0){
            resultMap.put("delResult","notexist");
        }else {
            BillService billService = new BillServiceImpl();
            if (billService.deleteBillById(delId)){
                resultMap.put("delResult","true");
            }else {
                resultMap.put("delResult","false");
            }
        }
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    private void modifyexe(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("billid");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String isPayment = req.getParameter("isPayment");
        String providerId = req.getParameter("providerId");
        if (!StringUtils.isNullOrEmpty(id)){
            BillService billService = new BillServiceImpl();
            if (billService.updateBill(id,billCode,productName,productDesc,productUnit,productCount,totalPrice,isPayment,providerId)){
                this.query(req,resp);
            }
        }
    }

    private void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(id)){
            BillService billService = new BillServiceImpl();
            Bill bill = billService.getBillById(id);
            req.setAttribute("bill",bill);
            req.getRequestDispatcher("/jsp/billmodify.jsp").forward(req,resp);
        }
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String isPayment = req.getParameter("isPayment");
        String providerId = req.getParameter("providerId");
        String providerName = req.getParameter("providerName");

        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount));
        bill.setTotalPrice(new BigDecimal(totalPrice));
        bill.setIsPayment(Integer.valueOf(isPayment));
        bill.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setCreationDate(new Date());
        bill.setProviderId(Integer.valueOf(providerId));
        bill.setProviderName(providerName);



        BillService billService = new BillServiceImpl();
        if (billService.addBill(bill)){
            resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query");
        }else {
            req.getRequestDispatcher("billadd.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void query(HttpServletRequest req, HttpServletResponse resp) {
        String qProName = req.getParameter("queryProductName");
        String qProId = req.getParameter("queryProviderId");
        String qIsPay = req.getParameter("queryIsPayment");
        String pageIndex = req.getParameter("pageIndex");
        List<Bill> billList = null;
        User user = null;
        BillService billService = new BillServiceImpl();
        int pageSize = 5;
        int currentPageNo = 1;
        String queryProductName = null;
        int queryProviderId = 0;
        int queryIsPayment = 0;


        if (qProName == null) {
            queryProductName = "";
        }else {
            queryProductName = qProName;
        }
        if (qProId != null && !qProId.equals("")) {
            queryProviderId = Integer.parseInt(qProId);;
        }
        if (qIsPay != null && !qIsPay.equals("")) {
            queryIsPayment = Integer.parseInt(qIsPay);;
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        int totalCount = billService.getBillCount(queryProductName,queryProviderId,queryIsPayment);
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        int totalPageCount = pageSupport.getTotalPageCount();
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        billList = billService.getBillList(queryProductName, queryProviderId, queryIsPayment, currentPageNo, pageSize);
        req.setAttribute("billList", billList);

        ProviderServiceImpl providerService = new ProviderServiceImpl();
        List<Provider> providerList = providerService.getProviderList();
        req.setAttribute("providerList",providerList);

        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);

        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment",queryIsPayment);

        user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        req.setAttribute("user", user);

        try {
            req.getRequestDispatcher("billlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getProviderList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("servletstart");
        List<Provider> providerList = null;
        ProviderService providerService = new ProviderServiceImpl();
        providerList = providerService.getProviderList();
        System.out.println("providerList(servlet)"+providerList);
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(providerList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }
}
